package com.demo.utils

import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.v4.content.FileProvider
import java.io.File

/**
 * Created by tangxin on 2017/8/7.
 */
open class PathUtils {

    companion object {

        /**
         * 获取根路径
         */
        fun getFileCacheDirectory(context: Context): File {
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                var cache: File? = null
                try {
                    cache = context.externalCacheDir
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }

                if (cache == null) {
                    val path = Environment.getExternalStorageDirectory().path + "/Android/data/" + context.packageName + "/cache/"
                    cache = File(path)
                }
                if (!cache.exists()) {
                    val canMake = cache.mkdir()
                    if (!canMake) {
                        return context.cacheDir
                    }
                }
                return cache
            } else {
                return context.cacheDir
            }
        }

        fun getImageFile(context: Context, name: String): File {
            val directory = File(getFileCacheDirectory(context).toString() + "/image")
            if (!directory.exists()) {
                directory.mkdir()
            }
            return File(directory, name)
        }

        /**
         * 获取指定图片路径
         */
        fun getVideoFile(context: Context, fileName: String): File {
            val directory = File(getFileCacheDirectory(context).toString() + "/video")
            if (!directory.exists()) {
                directory.mkdir()
            }
            return File(directory, fileName)
        }

        fun getVideoFile(context: Context): File {
            val directory = File(getFileCacheDirectory(context).toString() + "/video")
            if (!directory.exists()) {
                directory.mkdir()
            }
            return directory
        }

        fun getUri(context: Context, file: File): Uri {
            return getFileUri(context, file)
        }

        fun getApkUri(context: Context, apkName: String): Uri {
            return getFileUri(context, File(getFileCacheDirectory(context).toString() + "/apk/" + apkName))
        }

        fun getFileUri(context: Context, file: File): Uri {
            val uri: Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(context, "com.emm.yixun.mobile.fileprovider", file)
            } else {
                uri = Uri.fromFile(file)
            }
            return uri
        }

    }
}